package cn.com.tianpeidong.restaurantadmin.project.admin.desk.service.impl;

import cn.com.tianpeidong.restaurantadmin.common.exception.BusinessException;
import cn.com.tianpeidong.restaurantadmin.common.util.string.StringUtils;
import cn.com.tianpeidong.restaurantadmin.project.admin.desk.constant.DeskStatus;
import cn.com.tianpeidong.restaurantadmin.project.admin.desk.entity.DeskInfo;
import cn.com.tianpeidong.restaurantadmin.project.admin.desk.mapper.DeskMapper;
import cn.com.tianpeidong.restaurantadmin.project.admin.desk.service.IDeskService;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author tianpeidong
 * @version 创建时间: 19-6-8 下午7:37
 */
@Service
public class DeskServiceImpl implements IDeskService {

    @Autowired
    private DeskMapper deskMapper;


    @Override
    public DeskInfo getById(@NonNull Long id) {
        return deskMapper.getById(id);
    }

    @Override
    public List<DeskInfo> list() {
        return deskMapper.list();
    }

    @Override
    public DeskInfo newDesk(DeskInfo deskInfo) {
        String deskCode = deskInfo.getDeskCode();
        if (StringUtils.isEmpty(deskCode)) {
            throw new BusinessException("桌位编号为空");
        }
        DeskInfo dbData = deskMapper.checkDeskCodeExist(deskCode);
        if (! Objects.isNull(dbData)) {
            throw new BusinessException("桌位编号重复");
        }
        Integer maxPeopleNum = deskInfo.getMaxPeopleNum();
        if (maxPeopleNum <= 0) {
            throw new BusinessException("桌位人数不能小于零");
        }
        deskInfo.setStatus(DeskStatus.EMPTY.getCode());
        deskMapper.insert(deskInfo);
        return deskInfo;
    }

    @Override
    public DeskInfo updateDesk(@NonNull DeskInfo deskInfo) {
        DeskInfo dbData = deskMapper.getById(deskInfo.getId());
        if (Objects.isNull(dbData)) {
            throw new BusinessException("桌位不存在");
        }
        String deskCode = deskInfo.getDeskCode();
        if (StringUtils.isEmpty(deskCode)) {
            throw new BusinessException("桌位编号为空");
        }
        DeskInfo dbData1 = deskMapper.checkDeskCodeExist(deskCode);
        if (! Objects.isNull(dbData1) && dbData1.getId().compareTo(dbData.getId()) != 0) {
            throw new BusinessException("桌位编号重复");
        }
        Integer maxPeopleNum = deskInfo.getMaxPeopleNum();
        if (maxPeopleNum <= 0) {
            throw new BusinessException("桌位人数不能小于零");
        }
        deskMapper.update(deskInfo);
        return deskInfo;
    }

    @Override
    public DeskInfo deleteDesk(@NonNull DeskInfo deskInfo) {
        deskInfo.setStatus(DeskStatus.DELETE.getCode());
        deskMapper.updateStatus(deskInfo);
        return deskInfo;
    }

    @Override
    public DeskInfo updateDeskStatus(DeskInfo deskInfo) {
        deskMapper.updateStatus(deskInfo);
        return deskInfo;
    }
}
